package org.jflame.web.spring.controller;

import java.util.Map;

import org.springframework.boot.autoconfigure.web.ServerProperties;
import org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController;
import org.springframework.boot.web.error.ErrorAttributeOptions;
import org.springframework.boot.web.servlet.error.DefaultErrorAttributes;

import jakarta.servlet.http.HttpServletRequest;

/**
 * 覆盖默认的错误信息，与自定义错误信息统一
 * 
 * @author yucan.zhang
 */
public class MyErrorController extends BasicErrorController {

    public MyErrorController(ServerProperties serverProperties) {
        super(new DefaultErrorAttributes(), serverProperties.getError());
    }

    /* @Override
    @RequestMapping(produces = MediaType.TEXT_HTML_VALUE)
    public ModelAndView errorHtml(HttpServletRequest request, HttpServletResponse response) {
        HttpStatus status = getStatus(request);
        Map<String,Object> model = Collections
                .unmodifiableMap(getErrorAttributes(request, getErrorAttributeOptions(request, MediaType.TEXT_HTML)));
        response.setStatus(status.value());
        String html = "<html><head><title>Error Page</title></head><body style=\"padding:30px\"><h4>Error: %d - %s</h4><p>%s</p></body></html>";
        try {
            response.getWriter()
                    .print(String.format(html, model.get("status"), model.get("error"),
                            model.getOrDefault("message", "")));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }*/

    /* @Override
    public ResponseEntity<Map<String,Object>> error(HttpServletRequest request) {
        HttpStatus status = getStatus(request);
        if (status == HttpStatus.NO_CONTENT) {
            return new ResponseEntity<>(status);
        }
        // 与callresult保持统一
        Map<String,Object> body = getErrorAttributes(request,
                getErrorAttributeOptions(request, MediaType.APPLICATION_JSON));
        body.remove("timestamp");
        body.remove("path");
        if (body.containsKey("error") && !body.containsKey("message")) {
            body.put("message", body.remove("error"));
    
        }
        return new ResponseEntity<>(body, status);
    }*/
    /**
     * 覆盖输出的错误属性与callresult保持一致
     */
    protected Map<String,Object> getErrorAttributes(HttpServletRequest request, ErrorAttributeOptions options) {
        Map<String,Object> body = super.getErrorAttributes(request, options);
        body.remove("timestamp");
        body.remove("path");
        if (body.containsKey("error") && !body.containsKey("message")) {
            body.put("message", body.remove("error"));
        }
        return body;
    }

}
